<!--  线 + 柱混合图 -->
<template>
  <el-row :gutter="2">
    <el-col :span="2" class="col-container">
      <div id="legendContainer" class="legend-container">
        <!-- 在容器中写上每个颜色对应的含义 -->
        <div class="legend-item">
          <div class="legend-color" style="background-color: red"></div>
          <div class="legend-label">异常数据</div>
        </div>

        <div class="legend-item">
          <div class="legend-color" style="background-color: green"></div>
          <div class="legend-label">正常数据</div>
        </div>

        <div class="legend-item">
          <div class="legend-color" style="background-color: blue"></div>
          <div class="legend-label">预测数据</div>
        </div>
      </div>
    </el-col>
    <el-col :span="22">
      <div :id="id" :class="className" :style="{ height, width }"></div>
    </el-col>
  </el-row>
  <!-- {{rawyaxis }} -->
  <!-- {{ resultArray }} -->
  <!-- {{rawyaxis }}
  {{ab_index }}
  {{ y_pred }}
  {{ResultSource }} -->
  <!-- <p>dynamicnumber_section: {{dynamicnumber_section }}</p>
      <p>dynamicnumber_point: {{dynamicnumber_point }}</p> -->
  <!-- </el-card> -->
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import { useStore } from "vuex";
import { ref, computed, onMounted } from "vue";

const store = useStore();

// 在组件中访问 Vuex store 中的数组
const resultArray = store.state.resultArray;
// const parmsList = ref({algorithmname: 'gpr', train_size: 0.5, model_name: 'modelname1', satelliteName: '卫星1'});
const parmsList = ref(store.state.parmsList);
console.log(parmsList.value);
const algoReturnData = ref(store.state.algoReturnData);
console.log(algoReturnData.value);
const y_pred = algoReturnData.value[0]; //预测y数据
console.log("y_pred", y_pred);
const ab_index = algoReturnData.value[1];
console.log("ab_index)", ab_index);
const ab_point = algoReturnData.value[2];
console.log("ab_point", ab_point);
debugger;

// const train_size = (1 - TrainSize.value) * 100;
// const train_size = (1 - parmsList.value.train_size) * 100;
const train_size = (1 - parmsList.value.train_size) * 100;

// 从数组中获取百分之 x 的数据（与train_size相关）
function getPercentageOfArray(arr, percentage) {
  if (!Array.isArray(arr) || percentage < 0 || percentage > 100) {
    // 处理无效输入
    return null;
  }

  const totalCount = arr.length; //获取数组长度
  // const countToExtract = Math.ceil((percentage / 100) * totalCount); //ceil：向上取整
  const countToExtract = Math.floor((percentage / 100) * totalCount);

  // 返回截取后的数组(使用负索引表示从数组末尾开始)
  return arr.slice(-countToExtract);
}

//获取原始数据数组最后一列
const lastColumn = resultArray[Object.keys(resultArray).pop()]; //原始y数据：选择的最后一列
console.log(lastColumn);

// 获取最后一列的后百分之X
// const train_size= 30;//设置train_size
const rawyaxis = getPercentageOfArray(lastColumn, train_size);
// const rawyaxis = getLastColumnBackPercent(resultArray, train_size);
console.log(rawyaxis);
// 获取到原始数据和预测数据后，遍历得到source格式
const ResultSource = rawyaxis.map((value, index) => [
  index + 1,
  value,
  y_pred[index],
]);

console.log(ResultSource);

const props = defineProps({
  id: {
    type: String,
    default: "errorChart",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
});

// const source = ref([
//   ["Mon", 120, 123],
//   ["Tue", 132, 129],
//   ["Wed", 101, 98],
//   ["Thu", 134, 137],
//   ["Fri", 90, 95],
//   ["Sat", 210, 205],
//   ["MonMon", 180, 250],
//   ["TueTue", 170, 270],
//   ["WedWed", 100, 220],
//   ["ThuThu", 130, 135],
//   ["FriFri", 170, 164],
//   ["SatSat", 230, 233],
// ]);
//换上发送给后端的dataset
let source = ref(ResultSource);
// let source_index = ref([0, 2, 4, 6, 9]);
// let get_source_index = ref([0, 1, 2, 3, 5, 8, 9]);
// let get_source_index = ref([0, 1, 2, 4, 8, 9, 11]);
//替换上后端返回的ab_index
let get_source_index = ref(ab_index);
//后端返回的ab_point

// let get_source_index = ref([5, 6, 7, 8, 9]);

const visualMapPieces: { gt: number; lt: number; color: string }[] = [];

const visualMapPieces_red: { gte: number; lte: number; color: string }[] = [];
const visualMapPieces_green: { gt: number; lt: number; color: string }[] = [];

const markAreaPieces: [{ xAxis: number }, { xAxis: number }][] = [];
const markLinePieces: { xAxis: number; lineStyle: { color: string } }[] = [];
const dynamicnumber_section: number[] = [];
const dynamicnumber_point: number[] = [];
const dynamicstring: string[] = [];

// const definetwoarray = () => {
//       if ( get_source_index.value[0] == 0 ){
//           findthosepoint(0);
//       }else if(get_source_index.value[0] != source_index.value.length - 1){
//         dynamicnumber_section.push(0);
//       }
//       for (let i = 1; i < get_source_index.value.length - 1; i++){
//         findthosepoint(i);
//       }
// }

// const findthosepoint= (inputIndex: number) => {
//   let outputIndex = inputIndex
//   for (let i = inputIndex; i < get_source_index.value.length; i++){
//       if(get_source_index.value[inputIndex + 1] = get_source_index.value[inputIndex] + 1){
//           outputIndex = outputIndex + 1;
//       }
//   }
//   if(outputIndex = inputIndex){
//     dynamicnumber_point.push(outputIndex);
//   }else{
//     dynamicnumber_section.push(inputIndex);
//     dynamicnumber_section.push(outputIndex);
//   }

// }

const option = {
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "cross",
    },
  },
  grid: {
    left: "7%",
    right: "8%",
    bottom: "13%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: source.value.map((item) => item[0]), // Use the array of days directly
  },
  yAxis: {
    type: "value",
    boundaryGap: false,
  },
  dataZoom: [
    {
      type: "slider",
      xAxisIndex: 0,
      filterMode: "none",
    },
    {
      type: "inside",
      xAxisIndex: 0,
      filterMode: "none",
    },
  ],
  //   visualMap: {
  //   show: false,
  //   dimension: 0,
  //   pieces: [
  //     { gt: 0, lte: source_index.value[0],  color: 'green'},
  //     { gt: source_index.value[0], lte: source_index.value[1],  color: 'red'},
  //     { gt: source_index.value[1], lte: source_index.value[2],  color: 'green'},
  //     { gt: source_index.value[2], lte: source_index.value[3], color: 'red' },
  //     { gt: source_index.value[3], lte: source_index.value[4], color: 'green' },
  //     { gt: source_index.value[4], lte: 9, color: 'red' },  // 添加这一行表示大于索引 9 的数据点标记为红色
  //     { gt: 9, lte: 10, color: 'green' },
  //     { gt: 10, lte: 11, color: 'blue' },  // 这里可以设置相对于索引 9 的数据点的颜色
  //   ],
  // },
  series: [
    {
      type: "line",
      smooth: 0.6,
      lineStyle: {
        // color: 'green',
        width: 2,
      },
      data: source.value.map((item) => item[1]), // Use the second column directly
      //     markLine: {
      //       // silent: true, // 不显示在图例中
      //       label: {
      //   show: true, // 显示标签文字
      //   formatter: '1', // 设置标签文字为 '1'
      // },
      //     data: [
      //       {

      //         xAxis: 9, // 索引 9 的位置
      //         lineStyle: {
      //           color: 'red', // 设置索引 9 处的标记颜色
      //         },
      //       },
      //     ],
      //     },
      // markArea: {
      //   itemStyle: {
      //     color: 'rgba(255, 173, 177, 0.4)',
      //   },
      //   data: [
      //     [
      //       {
      //         xAxis: source_index.value[0],
      //       },
      //       {
      //         xAxis: source_index.value[1],
      //       },
      //     ],
      //     [
      //       {
      //         xAxis: source_index.value[2],
      //       },
      //       {
      //         xAxis: source_index.value[3],
      //       }
      //     ]
      //   ],

      // },
    },
    {
      type: "line",
      smooth: 0.6,
      lineStyle: {
        color: "blue",
        width: 2,
      },
      data: source.value.map((item) => item[2]), // Use the third column directly
    },
  ],
};
const updatefigure = () => {
  dynamicnumber_section.push(0);
  console.log("ab_index.length", ab_index.length);
  if (ab_index.length !== 0) {
    console.log("ab_index.length", ab_index.length);
    definetwoarray();
    console.log("已标注异常点！");
  }
  // dynamicnumber_section.push(source.value.length - 1);
  for (let midIndex = 0; midIndex < dynamicnumber_section.length; midIndex++) {
    if (midIndex % 2 == 0) {
      visualMapPieces_green.push({
        gt: dynamicnumber_section[midIndex],
        lt: dynamicnumber_section[midIndex + 1],
        color: "green",
      });
    } else {
      visualMapPieces_red.push({
        gte: dynamicnumber_section[midIndex],
        lte: dynamicnumber_section[midIndex + 1],
        color: "red",
      });
      markAreaPieces.push([
        { xAxis: dynamicnumber_section[midIndex] },
        { xAxis: dynamicnumber_section[midIndex + 1] },
      ]);
    }
  }
  for (
    let midIndex_1 = 0;
    midIndex_1 < dynamicnumber_point.length;
    midIndex_1++
  ) {
    markLinePieces.push({
      xAxis: dynamicnumber_point[midIndex_1],
      lineStyle: {
        color: "red",
      },
    });
  }

  if (chart.value) {
    chart.value.setOption({
      visualMap: {
        show: false,
        dimension: 0,
        pieces: (
          visualMapPieces_red as { gte: number; lte: number; color: string }[]
        ).concat(
          visualMapPieces_green as { gt: number; lt: number; color: string }[]
        ),
      },
      series: [
        {
          type: "line",
          smooth: 0.6,
          lineStyle: {
            // color: 'green',
            width: 2,
          },
          data: source.value.map((item) => item[1]), // Use the second column directly
          markLine: {
            // silent: true, // 不显示在图例中
            label: {
              show: false, // 显示标签文字
              // formatter: '1', // 设置标签文字为 '1'
            },
            data: [
              //   {
              //     xAxis: 5, // 索引 9 的位置
              //      lineStyle: {
              //     color: 'red', // 设置索引 9 处的标记颜色
              //    },
              // },
              ...markLinePieces,
            ],
          },
          markArea: {
            itemStyle: {
              color: "rgba(255, 173, 177, 0.4)",
            },
            data: [...markAreaPieces],
          },
        },
        {
          type: "line",
          smooth: 0.6,
          lineStyle: {
            color: "blue",
            width: 2,
          },
          data: source.value.map((item) => item[2]), // Use the third column directly
        },
      ],
    });
  }
};

// chart.value?.setOption({
//   visualMap: {
//     dimension: 0,
//     pieces: visualMapPieces,
//   },
//     series: [
//   {
//     type: 'line',
//     smooth: 0.6,
//     lineStyle: {
//       // color: 'green',
//       width: 2,
//     },
//     data: source.value.map((item) => item[1]), // Use the second column directly
// //     markLine: {
// //       // silent: true, // 不显示在图例中
// //       label: {
// //   show: true, // 显示标签文字
// //   formatter: '1', // 设置标签文字为 '1'
// // },
// //     data: [
// //       {

// //         xAxis: 9, // 索引 9 的位置
// //         lineStyle: {
// //           color: 'red', // 设置索引 9 处的标记颜色
// //         },
// //       },
// //     ],
// //     },
//     markArea: {
//       itemStyle: {
//         color: 'rgba(255, 173, 177, 0.4)',
//       },
//       data: [
//         [
//           {
//             xAxis: source_index.value[0],
//           },
//           {
//             xAxis: source_index.value[1],
//           },
//         ],
//         [
//           {
//             xAxis: source_index.value[2],
//           },
//           {
//             xAxis: source_index.value[3],
//           }
//         ]
//       ],

//     },
//   },
//   {
//     type: 'line',
//     smooth: 0.6,
//     lineStyle: {
//        color: 'blue',
//       width: 2,
//     },
//     data: source.value.map((item) => item[2]), // Use the third column directly
//   },
// ],
//     })
// }

const definetwoarray = () => {
  let span = 1;
  for (
    let inputIndex = 0;
    inputIndex < get_source_index.value.length;
    inputIndex = inputIndex + span
  ) {
    // findthosepoint(i);
    let outputIndex = inputIndex;
    for (let i = inputIndex; i < get_source_index.value.length; i++) {
      if (get_source_index.value[i + 1] == get_source_index.value[i] + 1) {
        outputIndex = outputIndex + 1;
      } else {
        break;
      }
    }
    if (outputIndex == inputIndex) {
      dynamicnumber_point.push(get_source_index.value[inputIndex]);
      span = 1;
    } else {
      dynamicnumber_section.push(get_source_index.value[inputIndex]);
      dynamicnumber_section.push(get_source_index.value[outputIndex]);
      span = outputIndex - inputIndex + 1;
    }
  }
};

const chart = ref<any>("");
onMounted(() => {
  // 图表初始化
  chart.value = markRaw(
    echarts.init(document.getElementById(props.id) as HTMLDivElement)
  );
  if (chart.value) {
    chart.value.setOption(option);
    updatefigure();
  }

  // 大小自适应
  window.addEventListener("resize", () => {
    chart.value.resize();
  });
});
</script>

<style>
.col-container {
  position: relative; /* 设置 el-col 为相对定位，为了让 legend-container 可以相对于它进行定位 */
}

.legend-container {
  position: absolute;
  bottom: 10px; /* 距离底部的距离 */
  right: 0; /* 距离右侧的距离 */
  font-size: 12px; /* 调整字体大小 */
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.legend-color {
  width: 20px;
  height: 10px;
  margin-right: 5px;
}

.legend-label {
  /* 可以添加额外的样式，根据需要调整字体颜色、样式等 */
}
</style>
